<template>
  <div class="user-header">
    <el-button type="primary" @click="handleAdd">新增</el-button>
    <el-form :inline="true" :model="formInline">
      <el-form-item label="请输入">
        <!-- 使用 el-input 组件作为输入框 -->
        <el-input
          placeholder="请输入用户名"
          v-model="formInline.keyword"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="table">
    <el-table :data="tableData" style="width: 100%">
      <el-table-column
        v-for="item in tableLabel"
        :key="item.prop"
        :width="item.width ? item.width : 125"
        :prop="item.prop"
        :label="item.label"
      ></el-table-column>
      <el-table-column label="操作" fixed="right" min-width="120">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button type="danger" size="small" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="pager"
      background
      layout="prev,pager,next,size"
      size="small"
      :total="config.total"
      @current-change="handleChange"
    ></el-pagination>
  </div>
  <el-dialog
    v-model="dialogVisible"
    :title="action == 'add' ? '新增用户' : '编辑用户'"
    width="35%"
    :before-close="handleClose"
  >
    <!--需要注意的是设置了:inline="true"，
		会对el-select的样式造成影响，我们通过给他设置一个class=select-clearn
		在css进行处理-->
    <el-form :inline="true" :model="formUser" :rules="rules" ref="userForm">
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="formUser.name" placeholder="请输入姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年龄" prop="age">
            <el-input v-model.number="formUser.age" placeholder="请输入年龄" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item class="select-clearn" label="性别" prop="sex">
            <el-select v-model="formUser.sex" placeholder="请选择">
              <el-option label="男" value="1" />
              <el-option label="女" value="0" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="出生日期" prop="birth">
            <el-date-picker
              v-model="formUser.birth"
              type="date"
              placeholder="请输入"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-form-item label="地址" prop="addr">
          <el-input v-model="formUser.addr" placeholder="请输入地址" />
        </el-form-item>
      </el-row>
      <el-row style="justify-content: flex-end">
        <el-form-item>
          <el-button type="primary" @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="onSubmit">确定</el-button>
        </el-form-item>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, reactive, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
// 定义搜索关键词的响应式变量
const searchKeyword = ref("");
const tableData = ref([]);
const { proxy } = getCurrentInstance();

const getUserData = async () => {
  let res = await proxy.$api.getUserData(config);
  tableData.value = res.list.map((item) => ({
    ...item,
    sexLabel: item.sex === "1" ? "男" : "女",
  }));
  config.total = res.count;
  console.log(res);
};
const tableLabel = reactive([
  {
    prop: "name",
    label: "姓名",
  },
  {
    prop: "age",
    label: "年龄",
  },
  {
    prop: "sexLabel",
    label: "性别",
  },
  {
    prop: "birth",
    label: "出生日期",
    width: 200,
  },
  {
    prop: "addr",
    label: "住址",
    width: 700,
  },
]);
const formInline = reactive({
  keyword: "",
});
const config = reactive({
  name: "",
  total: 100,
  page: 1,
});
const handleSearch = () => {
  config.name = formInline.keyword;
  getUserData();
};
const handleChange = (page) => {
  config.page = page;
  getUserData();
};
//控制对话框是否显示
const dialogVisible = ref(false);
//新增和编辑共用一个窗口，所以通过设置action区分
const action = ref("add");
// 设置新增用户表单里面的默认值，如性别默认是男
const formUser = reactive({
  sex: "1",
});
//表单校验规则
const rules = reactive({
  name: [{ required: true, message: "姓名是必填项", trigger: "blur" }],
  age: [
    { required: true, message: "年龄是必填项", trigger: "blur" },
    { type: "number", message: "年龄必须是数字" },
  ],
  sex: [{ required: true, message: "性别是必选项", trigger: "change" }],
  birth: [{ required: true, message: "出生日期是必选项" }],
  addr: [{ required: true, message: "地址是必填项" }],
});
const handleDelete = async (val) => {
  // 显示确认删除的提示框，配置确认按钮和取消按钮文本以及提示类型
  await ElMessageBox.confirm("你确定要删除吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  });
  // 调用 API 删除用户数据
  //   debugger;
  console.log(val.id);
  await proxy.$api.deleteUser({ id: val.id });
  // 显示删除成功的提示信息
  ElMessage({
    showClose: true,
    message: "删除成功",
    type: "success",
  });
  // 重新获取用户数据
  await getUserData();
};
const handleClose = () => {
  dialogVisible.value = false;
  //   getUserData();
};
const handleCancel = () => {
  dialogVisible.value = false;
};
const handleAdd = () => {
  dialogVisible.value = true;
  action.value = "add";

  //   onSubmit();
};
const timeFormat = (time) => {
  // 直接使用传入的 time 创建 Date 对象
  const date = new Date(time);
  // 检查 date 是否为有效的日期对象
  if (isNaN(date.getTime())) {
    throw new Error("Invalid date");
  }
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  // 辅助函数，用于给小于 10 的数字添加前导 0
  const add = (m) => (m < 10 ? "0" + m : m);
  return `${year}-${add(month)}-${add(day)}`;
};
const onSubmit = () => {
  proxy.$refs["userForm"].validate(async (valid) => {
    if (valid) {
      let res = null;
      formUser.birth = /^\d{4}-\d{2}-\d{2}$/.test(formUser.birth)
        ? formUser.birth
        : timeFormat(formUser.birth);
      if (action.value === "add") {
        // console.log(formUser);
        res = await proxy.$api.addUser(formUser);
      } else {
        res = await proxy.$api.editUser(formUser);
      }
      if (res) {
        dialogVisible.value = false;
        proxy.$refs["userForm"].resetFields();
        getUserData();
      }
    } else {
      ElMessage({
        showClose: true,
        message: "请输入正确的内容",
        type: "error",
      });
    }
  });
};

const handleEdit = (val) => {
  action.value = "edit";
  dialogVisible.value = true;
  nextTick(() => {
    Object.assign(formUser, { ...val, sex: "" + val.sex });
  });
};
onMounted(() => {
  getUserData();
});
</script>

<style lang="less" scoped>
.user-header {
  display: flex;
  justify-content: space-between;
}

.table {
  position: relative;
  height: 520px;
  .pager {
    position: absolute;
    right: 10px;
    bottom: 20px;
  }
  .el-table {
    width: 100%;
    height: 500px;
  }
}
.el-form-item.select-clearn {
  display: flex;
}
</style>
